package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.service.IProductService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ProductReceiver {

    @Autowired
    private IProductService productService;

    /**
     * 监听并处理库存解锁消息
     *
     * @param orderNo 订单编号，用于标识需要解锁库存的订单
     * @param message RabbitMQ消息对象，包含消息的元数据信息
     * @param channel RabbitMQ通道，用于手动确认消息处理完成
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_UNLOCK, durable = "true"),
            key = MqConst.ROUTING_UNLOCK
    ))
    public void unlock(String orderNo, Message message, Channel channel) {
        if (StringUtils.isNotEmpty(orderNo)) {
            log.info("[商品服务]监听解锁库存消息：{}", orderNo);
            //解锁库存
            productService.unlock(orderNo);
        }

        //手动确认消息处理完成
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


        /**
     * 监听并处理减库存消息
     *
     * @param orderNo 订单编号，用于标识需要减库存的订单
     * @param channel RabbitMQ通道，用于手动确认消息
     * @param message RabbitMQ消息对象，包含消息的元数据信息
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_MINUS , durable = "true"),
            key = MqConst.ROUTING_MINUS
    ))
    public void minus(String orderNo, Channel channel, Message message) {
        if (StringUtils.isNotEmpty(orderNo)) {
            log.info("[商品服务]监听减库存消息：{}", orderNo);
            //扣减库存
            productService.minus(orderNo);
        }
        // 手动确认消息消费成功
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}